package com.seednia.foundation.framework.util;

import java.math.BigInteger;
import java.util.ArrayList;

public class NumberUtils {

	/**
	 * Returns an object, that can be either String representation of number or big int to Long 
	 * @param obj
	 * @return
	 */
	public static final Long toLong(Object obj)
	{
		if (obj == null) return null;
		if ( obj instanceof BigInteger)
			return  ((BigInteger)obj).longValue() ;
		else if ( obj instanceof Long)
			return (Long)obj;
		else if ( obj instanceof String)
			return Long.valueOf((String)obj);
		else if ( obj instanceof Integer)
			return Long.valueOf( (Integer)obj );
		else 
			return null;
	}
	
	/**
	 * Returns all the possible integers which any of the bit is set in the value.
	 * @param maxDecNum
	 * @param val
	 * @return
	 */
	public static Integer[] possibleBitSetIntegers(int maxDecNum, int val) {
		if (val < 0)
			return null;
		ArrayList<Integer> retval = new ArrayList<Integer>(); 
		for (int j=1; j <= maxDecNum; j++) {
			if ( (val & j) > 0) {
				retval.add(j);
			}
		}
		return retval.toArray(new Integer[retval.size()]);
	}
	
	/**
	 * Check whether a string can be converted to an integer number
	 * @param i
	 * @return
	 */
	public static boolean isParsableToLong(String text) {
		try {
			Long.parseLong(text);
			return true;
		} catch (NumberFormatException nfe) {
			return false;
		}
	}
}
